//
//  taskListDetailVC.m
//  SQLiteTesting
//
//  Created by kitinat on 1/28/13.
//  Copyright (c) 2013 EGA. All rights reserved.
//
#import "EGAAppDelegate.h"

#import "taskListDetailVC.h"

#import "showFileVC.h"

#import "ARC_DB.h"

#import "UIViewController+MJPopupViewController.h"

#import "talkFirstStepVC.h"

#import "talkSecondStepVC.h"

#import "forwardCommandVC.h"

#import "EGAUtility.h"


@interface taskListDetailVC ()
{
    UIViewController* popoverContent;
    UIView *popoverView;
}


@end

@implementation taskListDetailVC

@synthesize DocID;
@synthesize EmpID;


@synthesize wvTaskTraveler;


@synthesize lbTaskDetail1;
@synthesize lbTaskDetail2;
@synthesize lbTaskDetail3;
@synthesize lbTaskDetail4;
@synthesize lbTaskDetail7;
@synthesize lbTaskDetail8;
@synthesize lbTaskDetail9;
@synthesize lbTaskDetail10;

@synthesize btnTalkFirst;
@synthesize btnTalkSecond;
@synthesize btnCommand;

@synthesize lbDocName;


@synthesize lbDocRecieveDate;
@synthesize lbDocDate;
@synthesize lbDocSerial;
@synthesize lbIsDuaDateColon;
@synthesize lbIsDueDate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}










NSArray * arrTaskDetail;


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self dismissKeyboard];
    
    ARC_DB * DB = [[ARC_DB alloc]init];
    
    if ([DB isHasTaskDetailInDB:DocID] && ![DB internetConnected])
    {
        [self alertNotConnect];
        arrTaskDetail = [DB getTaskDetail:DocID];
        [self setTaskDetailAndHiddenOrNot3Button];
        [self loadRequestWebview];
    }
    else
    {
        [self refresh];
    }
    
    
    
}




#pragma dismisskeyboard
- (void)dismissKeyboard {
    [self globalResignFirstResponder];
}
- (void) globalResignFirstResponder {
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    for (UIView * view in [window subviews]){
        [self globalResignFirstResponderRec:view];
    }
}
- (void) globalResignFirstResponderRec:(UIView*) view {
    if ([view respondsToSelector:@selector(resignFirstResponder)]){
        [view resignFirstResponder];
    }
    for (UIView * subview in [view subviews]){
        [self globalResignFirstResponderRec:subview];
    }
}





-(void)refresh
{
    ARC_DB * DB = [[ARC_DB alloc]init];
    if([DB internetConnected])
    {
        [DB saveTaskDetail:DocID taskUserOrAdmin:@"user" empID:EmpID];
        arrTaskDetail = [DB getTaskDetail:DocID];
        [self setTaskDetailAndHiddenOrNot3Button];
    }
    else
    {
        [self alertNotConnect];
    }
    [self loadRequestWebview];
}



-(void)loadRequestWebview
{
    NSString *strUrl=[NSString stringWithFormat:@"http://%@Travel.aspx?docID=",serviceUrl];
    NSString *urlAddress =[strUrl stringByAppendingString:DocID];
    
    NSURL *url = [NSURL URLWithString:urlAddress];

    
    
    
    
    //set stored file name
    NSString * storeFileName = [NSString stringWithFormat:@"%@.txt",DocID] ;
    ARC_DB * DB = [[ARC_DB alloc]init];
    //update webview
    if([DB internetConnected])
    {
        NSString *HTML = [NSString stringWithContentsOfURL: url encoding: NSUTF8StringEncoding error: nil];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:storeFileName];
        [HTML writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
        [wvTaskTraveler loadHTMLString: HTML baseURL: url];
    }
    //check if file exist or not
    else if([self isHasFileWithSavedFileName:storeFileName])
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:storeFileName];
        NSString *HTML = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
        [wvTaskTraveler loadHTMLString: HTML baseURL: url];
    }
    
    
    
    
}






-(BOOL)isHasFileWithSavedFileName:(NSString*)savedFileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:savedFileName];
    
    //if file not exist in document
    if([fileManager fileExistsAtPath:writablePath])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}






-(void)setTaskDetailAndHiddenOrNot3Button
{
    NSDictionary*dicForEachRow = [arrTaskDetail objectAtIndex:0];
    lbTaskDetail1.text = [dicForEachRow objectForKey:@"Doc_Register"];
    //lbTaskDetail2.text = [dicForEachRow objectForKey:@"Doc_Subject"];
    //lbTaskDetail3.text = [dicForEachRow objectForKey:@"Description"];
    lbTaskDetail4.text = [dicForEachRow objectForKey:@"Velocity"];
    lbTaskDetail7.text = [dicForEachRow objectForKey:@"Recorder"];
    lbTaskDetail8.text = [dicForEachRow objectForKey:@"StartDate"];
    lbTaskDetail9.text = [dicForEachRow objectForKey:@"DueDate"];
    
    
    
    int len = [[dicForEachRow objectForKey:@"Doc_Subject"] length];
    NSLog(@"len sub%d",len);
    if (len > 60){
        [_btSubject setFrame:CGRectMake(188, 93, 470,50)];
    }
    else
    {
        [_btSubject setFrame:CGRectMake(188, 95, 470,25)];
    }
    if (len<160) {
        // _subImgPop.hidden=YES;
    }
    UILabel *buttonLabel = [[UILabel alloc] initWithFrame:_btSubject.bounds];
    buttonLabel.numberOfLines = 2;
    // buttonLabel.text =@"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    buttonLabel.text =[dicForEachRow objectForKey:@"Doc_Subject"];
    // _btSubject.backgroundColor=[UIColor redColor];
    [buttonLabel setTextColor:[UIColor darkGrayColor]];
    [_btSubject addSubview:buttonLabel];
    [_btSubject bringSubviewToFront:buttonLabel];
    
    int   lenDex = [[dicForEachRow objectForKey:@"Description"] length];
    NSLog(@"len des%d",lenDex);
    if (lenDex > 60){
        [_btDes setFrame:CGRectMake(188, 140, 470,60)];
    }
    else
    {
        [_btDes setFrame:CGRectMake(188, 144, 470,25)];
    }
    if (lenDex<160) {
        //  _desImgPop.hidden=YES;
    }
    UILabel *buttonLabelDes  = [[UILabel alloc] initWithFrame:_btDes.bounds];
    buttonLabelDes.numberOfLines = 2;
    buttonLabelDes.text =[dicForEachRow objectForKey:@"Description"];
    //buttonLabelDes.text =@"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
    [buttonLabelDes setTextColor:[UIColor darkGrayColor]];
    [_btDes addSubview:buttonLabelDes];
    [_btDes bringSubviewToFront:buttonLabelDes];
    
    lbDocSerial.text = [dicForEachRow objectForKey:@"Doc_Serial"];
    EGAUtility * Util = [[EGAUtility alloc]init];
    lbTaskDetail8.text = [Util getDateTh:([dicForEachRow objectForKey:@"StartDate"])];
    lbTaskDetail9.text =[Util getDateTh:([dicForEachRow objectForKey:@"DueDate"])];
    lbDocDate.text= [Util getDateTh:([dicForEachRow objectForKey:@"Doc_Date"])];
    lbDocRecieveDate.text=[Util getDateTh:([dicForEachRow objectForKey:@"Doc_ReceiveDate"])];
    
    NSString * IsDusDate =[dicForEachRow objectForKey:@"IsDueDate"];    if ([IsDusDate isEqualToString:@"0"])
    {
        lbIsDuaDateColon.text=@"";
        lbIsDueDate.text=@"";
        lbTaskDetail9.text=@"";
    }

    

    
    //set doc title
    lbDocName.text = [NSString stringWithFormat:@"[งานของฉัน] %@", [dicForEachRow objectForKey:@"Doc_Subject"]];
    
    NSString * taskStatus = [dicForEachRow objectForKey:@"TaskStatus"];
    if ([taskStatus isEqualToString:@"1"])
    lbTaskDetail10.text = @"ยังไม่ดำเนินการ";
    else if ([taskStatus isEqualToString:@"4"])
    lbTaskDetail10.text = @"ดำเนินการเรียบร้อย";
    
    
    
    
    //set button of show attachment file
    NSArray *arrDocBookBeforeSign_ID    = [[dicForEachRow objectForKey:@"DocBookBeforeSign_ID"] componentsSeparatedByString:@";"];
    NSArray *arrDocBookBeforeSign_Name  = [[dicForEachRow objectForKey:@"DocBookBeforeSign_Name"] componentsSeparatedByString:@";"];
    
    if([arrDocBookBeforeSign_ID count]!=1)
    {
        for(int i = 0; i <= [arrDocBookBeforeSign_ID count]-2 ; i++)
        {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            if (i == 0)
                [button setFrame:CGRectMake(212, 288, 100,25 )];
            else
                [button setFrame:CGRectMake(((i+1)*100)+112, 288, 100, 25 )];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            
            NSString * strBtnTitle = [NSString stringWithFormat:@" %@  ",arrDocBookBeforeSign_Name[i]];
            [button setTitle:strBtnTitle forState:UIControlStateNormal];
            
            [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
            
            button.accessibilityLabel = [NSString stringWithFormat:@"%@|%@",arrDocBookBeforeSign_ID[i],arrDocBookBeforeSign_Name[i]];
            
            //set button image
            NSArray     * arrFileInfo           = [button.accessibilityLabel componentsSeparatedByString:@"|"];
            NSString    * fileID                = arrFileInfo[0];
            NSString    * fileNameAndType       = arrFileInfo[1];
            NSArray     * arrFileNameAndType    = [fileNameAndType componentsSeparatedByString:@"."];
            NSString    * fileType              = arrFileNameAndType[   [arrFileNameAndType count]-1   ];
            NSString    *  storeFileName = [NSString stringWithFormat:@"%@%@.%@",@"task",fileID,fileType];
            UIImage *img ;
            if([self isHasFileWithSavedFileName:storeFileName])
                img = [UIImage imageNamed:@"open.png"];
            else
                img = [UIImage imageNamed:@"save.png"];
            [button setImage:img forState:UIControlStateNormal];
            
            button.titleLabel.font = [UIFont systemFontOfSize:15];
            
            [self.view addSubview:button];
            
        }
    }
    
    
    
    //set button of show attachment file
    NSArray *arrDocAttachment_ID    = [[dicForEachRow objectForKey:@"DocAttachment_ID"] componentsSeparatedByString:@";"];
    NSArray *arrDocAttachment_Name  = [[dicForEachRow objectForKey:@"DocAttachment_Name"] componentsSeparatedByString:@";"];

    if([arrDocAttachment_ID count]!=1)
    {
        for(int i = 0; i <= [arrDocAttachment_ID count]-2 ; i++)
        {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            if (i == 0)
                [button setFrame:CGRectMake(212, 312, 100,25 )];
            else
                [button setFrame:CGRectMake(((i+1)*100)+112, 312, 100, 25 )];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            
            NSString * strBtnTitle = [NSString stringWithFormat:@" %@  ",arrDocAttachment_Name[i]];
            [button setTitle:strBtnTitle forState:UIControlStateNormal];
            
            [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        
            button.accessibilityLabel = [NSString stringWithFormat:@"%@|%@",arrDocAttachment_ID[i],arrDocAttachment_Name[i]];
            
            //set button image
            NSArray     * arrFileInfo           = [button.accessibilityLabel componentsSeparatedByString:@"|"];
            NSString    * fileID                = arrFileInfo[0];
            NSString    * fileNameAndType       = arrFileInfo[1];
            NSArray     * arrFileNameAndType    = [fileNameAndType componentsSeparatedByString:@"."];
            NSString    * fileType              = arrFileNameAndType[   [arrFileNameAndType count]-1   ];
            NSString    *  storeFileName = [NSString stringWithFormat:@"%@%@.%@",@"task",fileID,fileType];
            UIImage *img ;
            if([self isHasFileWithSavedFileName:storeFileName])
                img = [UIImage imageNamed:@"open.png"];
            else
                img = [UIImage imageNamed:@"save.png"];
            [button setImage:img forState:UIControlStateNormal];
            
            button.titleLabel.font = [UIFont systemFontOfSize:15];
            
            [self.view addSubview:button];

        }
    }
    
    
    //set hidden or not 3 button
    NSString * IsFirst      = [dicForEachRow objectForKey:@"IsFirst"];
    NSString * IsSecond     = [dicForEachRow objectForKey:@"IsSecond"];
    NSString * IsCommand    = [dicForEachRow objectForKey:@"IsCommand"];
    
    if([IsFirst isEqualToString:@"True"])
        btnTalkFirst.hidden = NO;
    else if ([IsFirst isEqualToString:@"False"])
        btnTalkFirst.hidden = YES;
    
    if([IsSecond isEqualToString:@"True"])
        btnTalkSecond.hidden = NO;
    else if ([IsSecond isEqualToString:@"False"])
        btnTalkSecond.hidden = YES;
    
    if([IsCommand isEqualToString:@"True"])
        btnCommand.hidden = NO;
    else if ([IsCommand isEqualToString:@"False"])
        btnCommand.hidden = YES;

    

}


- (void)buttonPressed:(UIButton *)sender
{
        self.SFVC = [[showFileVC alloc] initWithNibName:@"showFileVC" bundle:nil];
    
        self.SFVC.fileInfo = sender.accessibilityLabel;
        self.SFVC.TalkOrTask = @"task";
    [self presentPopupViewController:self.SFVC animationType:0 popupType:@"showFileTask"];
}

-(void)alertNotConnect
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ไม่สามารถเชื่อมต่อกับเซิฟเวอร์"
                                                    message:@"ทำให้ไม่สามารถอัพเดทข้อมูล"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}






- (IBAction)refreshTouch:(id)sender {
    [self refresh];
    [self loadRequestWebview];
}
















- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}








- (IBAction)talkFirstStepTouch:(id)sender {
    talkFirstStepVC *talkFirstVC = [[talkFirstStepVC alloc] initWithNibName:@"talkFirstStepVC" bundle:nil];
    talkFirstVC.DocID = DocID;
    [self presentPopupViewController:talkFirstVC animationType:0 popupType:@"talk"];
}

- (IBAction)talkSecondStepTouch:(id)sender {
    talkSecondStepVC *talkSecondVC = [[talkSecondStepVC alloc] initWithNibName:@"talkSecondStepVC" bundle:nil];
    talkSecondVC.DocID = DocID;
    talkSecondVC.EmpID = EmpID;
    [self presentPopupViewController:talkSecondVC animationType:0 popupType:@"talk"];
}

- (IBAction)nextCommandTouch:(id)sender {
    forwardCommandVC *FCVC = [[forwardCommandVC alloc] initWithNibName:@"forwardCommandVC" bundle:nil];
    FCVC.DocID = DocID;
    FCVC.EmpID = EmpID;
    FCVC.delegate = self;
    [self presentPopupViewController:FCVC animationType:0 popupType:@"forwardCommand"];
}








//delegate method
-(void)didCloseOrCommand
{
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
    [self refresh];
}









- (void)dealloc {

    [_btPopSub release];
    [_btPopDes release];
   
    [_btSubject release];
    [_btDes release];
    [super dealloc];
}
- (IBAction)popSubShow:(id)sender {
    CGRect popRect ;
    popoverContent = [[UIViewController alloc] init];
    popRect = CGRectMake(123,168,_btSubject.frame.size.width,_btSubject.frame.size.height);
    popoverView = [[UIView alloc] initWithFrame:popRect];
    popoverView.backgroundColor = [UIColor whiteColor];
    popoverContent.view = popoverView;
    popoverContent.contentSizeForViewInPopover = CGSizeMake(500, 150);
    UIPopoverController *desPop = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
    UITextView *stw=[[UITextView alloc] initWithFrame:CGRectMake(10, 10, 500, 150)];
    [stw setTextColor:[UIColor darkGrayColor]];
    stw.backgroundColor = [UIColor clearColor];
    
    
    [popoverView addSubview:stw];
    
    [popoverContent release];
    
    
    stw.font = [UIFont systemFontOfSize:17.0];
    NSDictionary*dicForEachRow = [arrTaskDetail objectAtIndex:0];
    stw.text=[dicForEachRow objectForKey:@"Doc_Subject"];
    [stw setTextColor:[UIColor darkGrayColor]];
    
    //  int len = [[dicForEachRow objectForKey:@"Doc_Subject"] length];
    //  if (len > 160){
    [desPop presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    // }
}

- (IBAction)popDesShow:(id)sender {
    CGRect popRect ;
    popoverContent = [[UIViewController alloc] init];
    popRect = CGRectMake(123,210,_btDes.frame.size.width,_btDes.frame.size.height);
    popoverView = [[UIView alloc] initWithFrame:popRect];
    popoverView.backgroundColor = [UIColor whiteColor];
    popoverContent.view = popoverView;
    popoverContent.contentSizeForViewInPopover = CGSizeMake(500, 150);
    UIPopoverController *desPop = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
    UITextView *stw=[[UITextView alloc] initWithFrame:CGRectMake(10, 10, 500, 150)];
    [stw setTextColor:[UIColor darkGrayColor]];
    stw.backgroundColor = [UIColor clearColor];
    
    
    [popoverView addSubview:stw];
    
    [popoverContent release];
    
    
    stw.font = [UIFont systemFontOfSize:17.0];
    NSDictionary*dicForEachRow = [arrTaskDetail objectAtIndex:0];
    stw.text=[dicForEachRow objectForKey:@"Description"];
    [stw setTextColor:[UIColor darkGrayColor]];
    
    // int len = [[dicForEachRow objectForKey:@"Description"] length];
    //if (len > 160){
    [desPop presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    //  }


}
@end
